package com.wuyou.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.wuyou.api.AdvertiseServiceFeign;
import com.wuyou.config.AlipayConfig;
import com.wuyou.domain.AlipayBo;
import com.wuyou.domain.Result;
import com.wuyou.dto.AdvPayLogDTO;
import com.wuyou.dto.AdvertisingDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * description
 * author 刘雷雨
 * date 2022/9/10 0:08
 * version 1.0
 **/
@RestController
public class AdvAlipayUrlController {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AdvertiseServiceFeign advertiseServiceFeign;
    /**
     * 同步回调
     * @param request
     * @param out_trade_no 商户订单号
     * @param trade_no 支付宝交易号
     * @param total_amount 付款金额
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("returnUrl")
    public Result returnUrl(HttpServletRequest request, String out_trade_no,
                            String trade_no, String total_amount) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //校验数字签名是否合法
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——支付成功——
        if(signVerified) {
            return Result.OK().setData(new AlipayBo(out_trade_no,trade_no,total_amount));
        }else {
            return Result.ERROR();
        }
    }


    /**
     * 异步回调
     * @param request
     * @param out_trade_no 商户订单号
     * @param trade_no 支付宝交易号
     * @param trade_status 交易状态
     * @return
     */
    @RequestMapping("notifyUrl")
    public String notifyUrl(HttpServletRequest request,String out_trade_no,String trade_no,String trade_status) throws AlipayApiException {

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        //验证数字签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        if(signVerified) {//验证成功
            ValueOperations<String, String> stringRedis = stringRedisTemplate.opsForValue();

            if(trade_status.equals("TRADE_FINISHED")){//交易关闭
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){//交易成功
                String[] refund_fees = requestParams.get("refund_fee");
                if (refund_fees != null) {
                    //退款请求
                    //修改订单号
                }else {
                    //付款请求
                    //判断该笔订单是否在商户网站中已经做过处理,
                    if (!stringRedisTemplate.hasKey("orderNum"+out_trade_no)) {
                        //修改广告信息
                        AdvertisingDTO advertisingDTO = new AdvertisingDTO()
                                .setOrderNum(out_trade_no)
                                .setTradeNo(trade_no)
                                .setStatus(1);
                        advertiseServiceFeign.updateAdvertisingByOrderNum(advertisingDTO);
                        //修改广告订单信息
                        AdvPayLogDTO advPayLogDTO = new AdvPayLogDTO()
                                .setOrderNum(out_trade_no)
                                .setTradeNo(trade_no)
                                .setStatus(1);
                        advertiseServiceFeign.updateAdvPayInfoByOrderNum(advPayLogDTO);
                        stringRedisTemplate.opsForValue().set("orderNum"+out_trade_no,out_trade_no.toString(),5, TimeUnit.MINUTES);
                    }
                    //注意：
                    //付款完成后，支付宝系统发送该交易状态通知
                }
            }
            return "success";
        }else  {//验证失败
            return "fail";
            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }
}
